# _*_ coding: utf-8 _*_
__author__ = 'HaoGe'
from django.views.generic import ListView, TemplateView, View
from users.models import GroupProfile,Profile
from django.contrib.auth.models import User, Group, Permission
from django.http import HttpResponse, JsonResponse
from django.urls import reverse
from django.shortcuts import redirect, render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth.mixins import LoginRequiredMixin
from confs.Log import logger
from django.shortcuts import render_to_response,HttpResponse

# 用户组列表
class GroupListView(LoginRequiredMixin, ListView):
    template_name = 'group/group_list.html'
    #model = GroupProfile
    #paginate_by = 8
    #ordering = 'id'

    #def get_context_data(self, **kwargs):
    #    context = super(GroupListView, self).get_context_data(**kwargs)#

    #    context['page_range'] = self.get_pagerange(context['page_obj'])
    #    return context

    def get(self, request):
        object_list = GroupProfile.objects.all()
        logger.info(object_list)
        return render_to_response('group/group_list.html', locals())

    def get_pagerange(self, page_obj):
        current_index = page_obj.number
        max_pages = page_obj.paginator.num_pages + 1
        #print(max_pages)

        start = current_index - 1
        end = current_index + 2

        if end > max_pages:
            start = start - 1
            end = max_pages

        if start < 1:
            if end < max_pages:
                end = end + 1
            start = 1

        return range(start, end)

class GroupAPIJsonView(LoginRequiredMixin, ListView):
	def get(self,request):
		jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
		groups = GroupProfile.objects.all()
		for s in groups:
			hosts = len(s.group.user_set.all())
			#hosts = ','.join([m.hostname for m in hosts ])
			m = {"id": s.group.id,"groupname":s.group.name,"hosts":hosts,"info":s.info}
			jsondata["data"].append(m)

		return JsonResponse(jsondata)

# 创建用户组
class GroupCreateView(LoginRequiredMixin, TemplateView):
    template_name = 'group/group_create.html'

    def get(self, request):
        users = [{"value": m.user.id, "name": m.name} for m in Profile.objects.all()]
        jsondata = {"users": users}

        return JsonResponse(jsondata)

    def post(self, request):

        ret = {'status': 0}
        ret['msg'] = '添加用户组成功'

        group = Group()
        group.name = request.POST.get('name')
        group.save()

        group_profile = GroupProfile()
        group_profile.group = group
        group_profile.info = request.POST.get('info')
        group_profile.save()

        members_list = request.POST.getlist('members',[])
        if members_list != ['']:
            for user_id in members_list:
                User.objects.get(pk=user_id).groups.add(group)
            print('用户组oK...')

        return JsonResponse(ret)



# 删除用户组
class GroupDeleteView(LoginRequiredMixin, View):

    def post(self, request):
        ret = {'status': 0}
        gid = request.POST.get('group_id', None)

        try:
            Group.objects.get(id=gid).delete()
            ret['msg'] = '删除用户组成功'
        except User.DoesNotExist:
            ret['status'] = 1
            ret['msg'] = '此用户组不存在，删除失败'
        except Exception:
            ret['status'] = 1
            ret['msg'] = '其他错误，请联系系统管理员'

        return JsonResponse(ret)


# 更新用户组
class GroupModifyView(LoginRequiredMixin, TemplateView):
    template_name = 'group/group_modify.html'

    def get(self, request):
        id = request.GET.get('id')
        group = Group.objects.get(id=id)
        gp = GroupProfile.objects.get(group=group)
        data_list = []
        userid_list = [x.id for x in group.user_set.all()]

        users = Profile.objects.all()
        for s in users:
            if s.user.id in userid_list:
                data_list.append({"name": s.name, "value": s.user.id, "selected": True})
            else:
                data_list.append({"name": s.name, "value": s.user.id})

        jsondata = {"data_list": data_list,"id":group.id,"name":group.name,"info":gp.info}

        return JsonResponse(jsondata)

    def post(self, request):

        ret = {"status":0,"msg":"用户组修改成功"}

        group_name = request.POST.get('name')
        users = request.POST.get('users').split(',')
        info = request.POST.get('info')
        gid = request.POST.get('id')
        print (users)

        group_obj = Group.objects.get(id=gid)
        group_obj.name = group_name
        group_obj.groupprofile.info = info
        group_obj.save()
        group_obj.groupprofile.save()
        us = User.objects.filter(id__in = users)
        group_obj.user_set.set(us)
        for user_id in users:
            group_obj.user_set.add(User.objects.get(pk=user_id))

        return  JsonResponse(ret)


# 用户组设置权限
class GroupSetPermView(LoginRequiredMixin, TemplateView):
    template_name = 'group/group_set_perm.html'

    def get_context_data(self, **kwargs):
        gid = self.request.GET.get('gid')
        context = super(GroupSetPermView, self).get_context_data(**kwargs)
        context['group_obj'] = Group.objects.get(pk=gid)
        context['perm_list'] = Permission.objects.all().exclude(name__regex='[a-zA-Z0-9]')

        return context

    def post(self, request):
        ret = {'status': 0}
        gid = request.POST.get('group_id')
        try:
            group = Group.objects.get(pk=gid)
            group.permissions.set(request.POST.getlist('perm_list[]'))
            ret['msg'] = '设置成功'
        except Exception:
            ret['status'] = 1
            ret['msg'] = '设置失败'

        return JsonResponse(ret)

